package pl.edu.uj.tcs.blef.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.LinkedList;
import java.util.Vector;

import pl.edu.uj.tcs.blef.protocol.BussyServerException;
import pl.edu.uj.tcs.blef.protocol.InvalidParametersException;

public final class Server extends Thread {
	private int port;
	private boolean running;
	private ServerSocket socket;
	private ServerListener serverListener;
	private LinkedList<Table> tables;
	
	public Server(int port) throws IOException{
		this.port = port;
		this.running = true;
		this.socket = new ServerSocket(port);
		this.tables = new LinkedList<Table>();
		this.serverListener = new ServerListener(this.socket);	
		GlobalSettings._MAIN_SERVER_ = this;
	}
	
	@Override
	public void run(){
		while(running){}
	}
	
	public Table registryTable(String tableName, String operator) throws BussyServerException, InvalidParametersException{
		if(tables.size() >= GlobalSettings._MAX_TABLES_) throw new BussyServerException();
		
		for(Table t: tables){
			if(t.getIdentifier().equals(tableName)) throw new InvalidParametersException();
		}
		
		try {
			Table result = new Table(tableName, operator);
			this.tables.add(result);
			return result;
		} catch (IOException e) { throw new InvalidParametersException(); }
	}
	
	public void removeTable(Table table){
		this.tables.remove(table);
	}
	
	public Vector<String> getTables(){
		Vector<String> result = new Vector<String>();
		for(Table t: tables){
			result.add(t.getIdentifier() + " " + t.getPort());
		}
		
		return result;
	}

	/**
	 * @param args Only one arg which is the server-port.
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		if(args.length != 1){
			System.out.println("TCS-Blef Server usage: [port]");
			System.exit(1);
		}
		
		int port = Integer.parseInt(args[0]);
		new Server(port).start();
		System.out.println("Server started at port " + args[0]);
	}

}
